const path = require('path');
const express = require('express');
const httpError = require('http-errors');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const helmet = require('helmet');
const methodOverride = require('method-override');
const request = require('request')

//internal modules
const routes = require('../routes/index.route');
const config = require('./config');

const app = express();

if (config.env === 'development') {
  app.use(logger('dev'));
}

// enable CORS - Cross Origin Resource Sharing
app.use(cors());

app.use('/invix', (req, res) => {
  const options = {
    url: 'https://inspect.invix.tech/',
  }
  request(options, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      res.send(body); // 将代理的响应返回给客户端
    } else {
      res.status(500).send('Error'); // 处理代理请求异常
    }
  });
})
// const corsConfig = {
//   origin: 'http://lean.invix.tech:8070',
//   Credential: true,
// }
// app.use(cors(corsConfig))

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cookieParser());
app.use(methodOverride());

// secure apps by setting various HTTP headers
// app.use(helmet());
app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

var distDir = '../../dist/';

app.use(express.static(path.join(__dirname, distDir)));

// const statisticMainChannelPath = config.statisticResource + '/mainChannel/';
// app.use(express.static(statisticMainChannelPath));


app.use(/^((?!(api)).)*/, (req, res) => {
  res.sendFile(path.join(__dirname, '../../dist/index.html'));
});


// API router
app.use('/api/', routes);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new httpError(404)
  return next(err);
});

// error handler, send stacktrace only during development
app.use((err, req, res, next) => {

  // customize Joi validation errors
  if (err.isJoi) {
    err.message = err.details.map(e => e.message).join("; ");
    err.status = 400;
  }

  res.status(err.status || 500).json({
    message: err.message
  });
  next(err);
});

module.exports = app;
